import apiClient from '@api/index';
import store from '@store/index';
import { setTokens, clearTokens } from '@store/token';
import { loginSuccess, logout as authLogout } from '@store/auth';

// 登录接口响应数据类型
interface LoginResponse {
  message: string;
  data: {
    access_token: string;
    refresh_token: string;
  };
  code: number;
  success: boolean;
}

// 登录函数
export const login = async (username: string, password: string): Promise<boolean> => {
  try {
    const response = await apiClient.post<LoginResponse>('/auth/login', { 
      username, 
      password 
    });
    
    const { data, success } = response.data;
    
    if (success && data && data.access_token) {
      // 存储 token
      store.dispatch(setTokens({
        accessToken: data.access_token,
        refreshToken: data.refresh_token
      }));
      
      // 更新认证状态
      store.dispatch(loginSuccess());
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('Login failed:', error);
    return false;
  }
};

// 登出函数
export const logout = (): void => {
  // 清除 token
  store.dispatch(clearTokens());
  // 更新认证状态
  store.dispatch(authLogout());
};

// 刷新 token 函数
export const refreshToken = async (): Promise<boolean> => {
  try {
    const state = store.getState();
    const refreshToken = state.token.refreshToken;
    
    if (!refreshToken) {
      return false;
    }
    
    const response = await apiClient.post<LoginResponse>('/auth/refresh', { 
      refresh_token: refreshToken 
    });
    
    const { data, success } = response.data;
    
    if (success && data && data.access_token) {
      // 存储 token
      store.dispatch(setTokens({
        accessToken: data.access_token,
        refreshToken: data.refresh_token
      }));
      
      // 更新认证状态
      store.dispatch(loginSuccess());
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('Refresh token failed:', error);
    return false;
  }
};